
//  Home.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/3/25.
//  Copyright © 2018年 YTYanK. All rights reserved.
//

import UIKit
import AVFoundation
import ZCycleView
import SwiftyJSON

protocol homeIconViewDelegate: class {
    func viewTapClick(view: UIView)
}

class homeIconView: UIView{
    let iconImgView = UIImageView()
    let title = UILabel()
    weak var delegate : homeIconViewDelegate?
    /* 设置homeIconview 各种样式*/
    public var setHomeIconViewBlock: ((_ view: homeIconView) -> ())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubViews()
    }

    
    
//   便利初始化器
//    convenience init(imageName: String, title: String, size: CGSize) {
//        self.init(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
//
//        self.setData(data: ["imageName": imageName, "title": title])
//
//
//    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupSubViews() {
        
//        self.backgroundColor = self.homeIconViewBgColor
        self.addSubview(iconImgView)
        self.addSubview(title)
        
//        iconImgView.topAlign(view: self, predicate: "0")
        iconImgView.centerXAlign(view: self, predicate: "0")
        iconImgView.centerYAlign(view: self, predicate: "-20")
//        iconImgView.backgroundColor = UIColor.red
        
        title.topVertically(view: iconImgView, predicate: "10")
        title.centerXAlign(view: self)
        title.backgroundColor = UIColor.clear
       
        let gesture = UITapGestureRecognizer(target: self, action: #selector(viewTap))
        self.addGestureRecognizer(gesture)
 
    }
    
//    public func setData(data: Dictionary<String, Any>) {
//        self.iconImgView.image = UIImage.init(named: data["imageName"] as! String)
//        self.title.text = data["title"] as? String
//    }
    public func setData(imgName: String, title: String) {
        self.iconImgView.image = UIImage.init(named: imgName)
        self.title.text = title
        self.setHomeIconViewBlock?(self)
    }
    
    @objc func viewTap(sender: UITapGestureRecognizer) {
        delegate?.viewTapClick(view: sender.view!)
    }
    
    
}



class Home: HMViewController,homeIconViewDelegate {

    // MARK: - 常量
    let describe = UILabel()
    let cycleView = ZCycleView()
    let iconBroadcast = UIImageView()
    let broadcast = ZCycleView()
    let log = homeIconView() // 日志
    let service = homeIconView() //服务
    let room = homeIconView() //诊室
    let remind = homeIconView() //提醒
    let person = homeIconView() //个人
    var isDoctor : Bool {
        get {
            if !HMLoginParam.share.user.isEmpty {
                let dic = HMLoginParam.share.user
                if (dic["doctorStatus"] as! Int) == 2 {
                    return true
                }else {
                    return false
                }
            }else {
                return false
            }
            
        }
    }    //是否医生用户 - 默认普通用户
    var imges = Array<UIImage>()
    
    func configHome() {
       self.navigationItem.title = "首页"
       self.tabBarController?.tabBar.isHidden = true
       let showTabBar: Bool = (self.tabBarController?.tabBar.isHidden)!
       // 记录导航高度
        configure.shareConfigure.navHeight = (self.navigationController?.navigationBar.bounds.height)!
        
        /***
           高度、宽度计算
         */
        let wHalf = self.view.wWidth/2
        let cH: CGFloat = 80  // cycleViewHeight
        let iH: CGFloat = 40  // iconBroadcastHeight
        let bW = self.view.wWidth - CGFloat(iH) - 10.0    // broadcastWidth
        
        let floatZero: CGFloat = 0
        
        let barH = navigationController?.navigationBar.wHeight
        let tabH = (showTabBar ? floatZero : (tabBarController?.tabBar.wHeight)!)
        let statusH = UIApplication.shared.statusBarFrame.height
        let surplusHeightHalf = (self.view.wHeight - ( CGFloat(barH!) + CGFloat(tabH) + CGFloat(statusH) + cH + iH*2 )) / 2
        let logHeightHalf = surplusHeightHalf/2 // 再分一次
        
        
        /***
           添加view
         */
        view.addSubview(describe)
        view.addSubview(cycleView)
        view.addSubview(log)
        view.addSubview(service)
        view.addSubview(room)
        view.addSubview(remind)
        view.addSubview(person)
        
        describe.topAlign(view: view, predicate: "0")
        describe.leadingAlign(view: view)
        describe.trailingAlign(view: view)
        describe.heightConstrain(predicate: "\(iH)")
        describe.text = "当前活跃医生"
        
  
        cycleView.topVertically(view: describe)
        cycleView.leadingAlign(view: view, predicate: "0")
        cycleView.trailingAlign(view: view, predicate: "0")
        cycleView.heightConstrain(predicate: "\(cH + iH)")
//        cycleView.placeholderImage = UIImage(named: "pl")
        cycleView.itemSize = CGSize(width: cH, height: cH) //每个选项的大小
        cycleView.itemZoomScale = 1 //当前个的大小
        cycleView.pageControlIsHidden =  true // 分页标记
//        cycleView.setImagesGroup( [UIImage(named: "weiBo"),UIImage(named: "weChat"),UIImage(named: "qq"),UIImage(named: "weiBo")])
        cycleView.addLayer(isAddLayer: (false,false,false,true), color: UIColor.gray, crude: 1, layout: (cH + iH,cH + iH))
        
        
     
        

       
        // 模块部分
       log.topVertically(view: cycleView, predicate:  "0")
       log.leadingAlign(view: view, predicate: "0")
       log.heightConstrain(predicate: "\(surplusHeightHalf)")
       log.widthConstrain(predicate: "\(wHalf)")
       log.setData(imgName: "journal", title: "健康日志")
       log.tag = 1001
       log.delegate = self
       log.addLayer(isAddLayer: (false,true,true,true), color: UIColor.gray, crude: 1, layout: (wHalf,surplusHeightHalf))
       
        if isDoctor {
            service.topVertically(view: cycleView, predicate: "0")
            service.leadingHorizontally(view: log, predicate: "0")
            service.widthConstrain(predicate: "\(wHalf)")
            service.heightConstrain(predicate: "\(logHeightHalf)")
            service.setData(imgName: "service", title: "医生服务")
            service.tag = 1002
            service.delegate = self
            service.addLayer(isAddLayer: (false,true,false,false), color: UIColor.gray, crude: 1, layout: (wHalf,logHeightHalf))
            
            room.topVertically(view: service, predicate: "0")
            room.leadingHorizontally(view: log, predicate: "0")
            room.widthConstrain(predicate: "\(wHalf)")
            room.heightConstrain(predicate: "\(logHeightHalf)")
            room.setData(imgName: "consultingRoom", title: "进入诊室")
            room.tag = 1004
            room.delegate = self
            room.addLayer(isAddLayer: (false,true,false,true), color: UIColor.gray, crude: 1, layout: (wHalf,logHeightHalf))
        }else {
            service.topVertically(view: cycleView, predicate:  "0")
            service.leadingHorizontally(view: log, predicate: "0")
            service.heightConstrain(predicate: "\(surplusHeightHalf)")
            service.widthConstrain(predicate: "\(wHalf)")
            service.setData(imgName: "serviceBig", title: "医生服务")
            service.tag = 1002
            service.delegate = self
            service.addLayer(isAddLayer: (false,true,false,true), color: UIColor.gray, crude: 1, layout: (wHalf,surplusHeightHalf))
        }
   
        
        
       remind.topVertically(view: log, predicate: "0")
       remind.leadingAlign(view: view, predicate: "0")
       remind.widthConstrain(predicate: "\(wHalf)")
       remind.heightConstrain(predicate: "\(surplusHeightHalf)")
       remind.setData(imgName: "remind", title: "提醒")
       remind.tag = 1003
       remind.delegate = self
       remind.addLayer(isAddLayer: (false,false,true,false), color: UIColor.gray, crude: 1, layout: (wHalf,surplusHeightHalf))
       
        
       person.topVertically(view: log, predicate: "0")
       person.leadingHorizontally(view: remind, predicate: "0")
       person.widthConstrain(predicate: "\(wHalf)")
       person.tag = 1110
       person.delegate = self
       person.heightConstrain(predicate: "\(surplusHeightHalf)")
       person.setData(imgName: "user", title: "个人中心")
        

    }
    
    func viewTapClick(view: UIView) {
        if view.tag == 1001 {

          let healthLog = HealthLog()
          self.pushViewController(healthLog, animated: true)
            
        }else if view.tag == 1110 {
            // 到个人信息页面

            NetRequestTool.shareInstance.met = .get
            NetRequestTool.request(url: "user/base-info", parameters: [:], success: { (json) in
               let dic = json["data"].dictionaryObject
               HMLoginParam.updateInfo(dic!)
               let personal = PersonalCenter()
               self.pushViewController(personal)
            }, fail: { (error, msg) in
               debugPrint("--->Home",error,msg)
            }) {}
            
        }else if view.tag == 1002{
//            let service = HMDoctorService()
//            self.pushViewController(service)
            
              let service = HMService()
              service.dataType = .TypeVisitDoctor
              self.pushViewController(service)
            
        }else if view.tag == 1003 {
            let city = HMRemind() //CitySelectorViewController()
            self.pushViewController(city)
        }else if view.tag == 1004 {
//            let room = HMConsultingRoom()
//            self.pushViewController(room)
            let service = HMService()
            service.dataType = .TypeVisitPatient
            self.pushViewController(service)
        }else {
            
        }
    }
    
    
    // MARK: - 周期
    override func viewDidLoad() {
        super.viewDidLoad()
        self.configHome()
        
        // 生活模式
        NetRequestTool.request(url: "user/live-mode-config", parameters: [:], success: { (json) in
            if !json["data"].isEmpty {
                HMLoginParam.share.liveMode = json["data"].arrayObject
            }
            
        }, fail: { (code, msg) in
            
        }) {
            
        }
        
        // 运动模式
        NetRequestTool.request(url: "user/sport-mode-config", parameters: [:], success: { (json) in
            if !json["data"].isEmpty {
             HMLoginParam.share.sportMode = json["data"].arrayObject
            }
        }, fail: { (code, msg) in
            
        }) {
            
        }
        
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
        
        var imageUrls = Array<String>()
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "user/online/doctor", parameters: [:], success: { (doctorJson) in
            
            let ary = doctorJson["data"].arrayValue
            for item in ary {
                let urlstr = configure.shareConfigure.IP_diagonal + item["iconUrl"].stringValue
                imageUrls.append(urlstr)
            }
            
            self.cycleView.setUrlsGroup(imageUrls)
            
        }, fail: { (code, err) in
            print("======xxxxxx获取图片失败")
        }) {
            
        }

        let dic =  NSDictionary.init(contentsOfFile: NSHomeDirectory() + "/Library/Caches/config.plist")
        if dic == nil {
            let queue =  DispatchQueue(label: "com.yty.url.template", qos: .background, attributes: [.concurrent, .initiallyInactive], autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.never, target: nil)
            queue.activate()
            //如果列表配置文件配置文件是空，就需要启动线程
            queue.async {
                NetRequestTool.request(url: "user/medicine/reminder/template", parameters: [:], success: { (reminderJson) in
                    if reminderJson["code"].intValue == 0 {
                        let path = NSHomeDirectory() + "/Library/Caches/config.plist"
                        let dic = reminderJson["data"].dictionaryObject
                        let nsDic = dic! as NSDictionary
                         nsDic.write(toFile: path, atomically: true)
//                        let nsDic2 = NSMutableDictionary.init(contentsOfFile: path)
                    }else {
                        
                    }
                }, fail: { (code, err) in }) {}
            }
        }
        
        // 这一个接口有问题
//        NetRequestTool.request(url:"doctor/audit-status", parameters: [:], success: { (json) in
//            print("home-->>",json)
//
//        }, fail: { (code, msg) in
//            print("home-->>",code, msg)
//        }) {}
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
